package com.scu.phototabuser.http;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.scu.phototabuser.App;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.util.CheckSumBuilder;
import com.scu.phototabuser.util.PreferenceUtil;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.scu.phototabuser.util.Predictions.checkNotNull;

/**
 * Created by tianfei on 2017/3/10.
 */

public class OkHttp3Methods {

    private static final MediaType FORM_CONTENT_TYPE
            =MediaType.parse("application/json;charset=utf-8");

    static final MediaType MEDIA_OBJECT_TYPE
            =MediaType.parse("application/octet-stream");

    static final MediaType JSON
            = MediaType.parse("application/json;charset=utf-8");

    static final MediaType TEXT
            = MediaType.parse("application/text;charset=utf-8");

    private static OkHttpClient client;
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

    private static final String CONTENT_TYPE="application/x-www-form-urlencoded;charset=utf-8";


    //get请求方式-include json
    public static String getMethod(String url, Map<String,String> paramMap,String encodingType) throws IOException{

        StringBuffer buffer=new StringBuffer();

        int pos=0;
        for (String key:paramMap.keySet()){
            if (pos>0){
                buffer.append("&");
            }
            buffer.append(String.format("%s=%s",key, URLEncoder.encode(paramMap.get(key),encodingType)));
            pos++;
        }
        //String params=buffer.toString();
        String requestUrl=String.format("%s?%s",url,buffer.toString());


        RequestBody body =RequestBody.create(FORM_CONTENT_TYPE,requestUrl);
        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    //post
    private static String postMethod(String url,@Nullable Map<String, String> params,
                                     String... token) throws IOException{

        String nonce =  getRandomNonce();
        String curTime = String.valueOf(System.currentTimeMillis());
        //String checkSum = checkNotNull(CheckSumBuilder.getCheckSum(Consts.AppSecret,url,Consts.AppKey,curTime, nonce));


        Headers.Builder headerBuilder=new Headers.Builder();

        headerBuilder.add("curTime", curTime)
                .add("nonce", nonce)
                //.add("checkSum",checkSum)
                .add("Content-Type", CONTENT_TYPE);

        if (token.length != 0) {
            headerBuilder.add("authorization",token[0]);
        }


        FormBody.Builder formBuilder=new FormBody.Builder();
        if (params!=null) {
            for (String k : params.keySet()) {
                formBuilder.add(k, params.get(k));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .headers(headerBuilder.build())
                .post(formBuilder.build())
                .build();

        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }

    }

    public static String UniversalPostRequest (String url, @NonNull Map<String,String> params) throws Exception{

        return postMethod(url,params);
    }

    public static String PostRequestWithToken(String url,@Nullable Map<String,String> params) throws Exception{

        return postMethod(url,params, PreferenceUtil.getToken());
    }

    private static String getRandomNonce(){

        Random random=new Random(System.currentTimeMillis());
        int ran=random.nextInt(102400)+1000;

        return ""+ran;
    }

}
